<?php
// # Check if the user is logged in
if ( !session_is_registered( 'user' ) ) exit();

// configuration
$supportedTags = array( 'Genre', 'Runtime', 'duration', 'Actors', 'ActorRoles', 'Director',
                        'Directors', 'Overview', 'Subtitle', 'Produced', 'Rating',
                        'Review', 'VolumeName', 'Watched', 'WatchedOn', 'Title' );

// # Getting the variables:
$q = $_GET['q'];
$library = $_GET['library'];
$page = $_GET['page'];
$edit = $_GET['edit'];
$volumeName = isset( $_GET['VolumeName'] ) ? $_GET['VolumeName'] : '';
$unwatchedOnly = isset( $_GET['Unwatched'] ) ? true : false;

$lib = new weebUILibrary( $_GET['library'] );

$tagsArray = $lib->tags( );
extract( $tagsArray );

if ( !$tag_Director ) $tag_Director = $tag_Directors;
if ( !$tag_Runtime ) $tag_Runtime = $tag_Duration;

// #####################################
// #####################################
// ##                                ###
// ##   This is where the different  ###
// ##        view types begin!       ###
// ##                                ###
// #####################################
// #####################################
$id = $_GET['id'];
// #####################################
// #  GENERAL VIEW, SEARCH & BROWSE   ##
// #####################################
if ( !$id )
{
    // # Volume filter + watched filter
    echo "<h5>VOLUME FILTER</h5>";
    echo "<ul>\n";
    // we display a link to filter on each volumename
    $volumes = weebUIVolumeManager::volumesList();
    foreach ( $volumes as $volume )
    {
        $label = $volume;
        if ( $volume != $volumeName )
        {
            $url = weebUIMovieListFunctions::movieListURL( array( 'VolumeName' => $volume ) );
            echo "<li><a href=\"{$url}\">{$label}</a></li>";
        }
        else
        {
            echo "<li><b>{$label}</b></li>";
        }
    }
    // default, no filter
    $url = weebUIMovieListFunctions::movieListURL( false, false, array( 'VolumeName' ) );
    echo "<li><a href=\"{$url}\">All</a></li>";
    echo "</ul>";

    echo "<h5>WATCHED FILTER</h5>";
    echo "<ul>\n";
    if ( !$unwatchedOnly )
        echo "<li><a href=\"" . weebUIMovieListFunctions::movieListURL( array( 'Unwatched' => '1' ) ) . "\">Unwatched only</a></li>";
    else
        echo "<li><b>Unwatched only</b></li>";

    if ( $unwatchedOnly )
        echo "<li><a href=\"" . weebUIMovieListFunctions::movieListURL( false, false, array( 'Unwatched' ) ) . "\">All</a></li>";
    else
        echo "<li><b>All</b></li>";
    echo "</ul>\n";

    // # Top of page, with search
    echo "<center>\n";
    echo "<b style=\"font-size: 24; margin-top: 20px;\">" . $lib->name . "</b>\n";
    echo "<br><br>\n";
    echo "<form method=\"GET\" action=\"$url\">\n";
    echo "<b>Search titles:</b>\n";
    echo "<input type=\"text\" name=\"q\" size=\"10\" value=\"" . $_POST['q'] . "\">\n";
    echo "<input type=\"hidden\" name=\"library\" value=\"$library\">\n";
    echo "<input type=\"hidden\" name=\"section\" value=\"library\">\n";
    echo "<input type=\"submit\" value=\"GO\">\n";
    echo "</form>\n";
    echo "<br>\n";

    // SQL Filters
    $SQLFilters = array();
    if ( $volumeName )
        $SQLFilters['VolumeName'] = " $tag_VolumeName LIKE '" . sqlite_escape_string( $volumeName ) . "' ";
    if ( $unwatchedOnly )
        $SQLFilters['Watched'] = " $tag_Watched NOT LIKE 'True' ";
    if ( $q )
        $SQLFilters['Search'] = " item_name LIKE '%{$q}%' ";
    if ( count( $SQLFilters ) )
        $SQLFilter = "WHERE" . implode( 'AND', $SQLFilters );

    // # Get the number of results from the database, to calculate number of pages
    $results = sqlite_fetch_single( $lib->query( "SELECT COUNT(*) AS count FROM items $SQLFilter" ) );

    // # Get the "limit per page" set in config.php, and calculate pages and sql string!
    $limit = $lib->pagelimit;

    if ( !$page ) $page = 1;
    if ( $limit != 0 )
    {
        $offset = ( ( $page * $limit ) - $limit );
        $pages = ( $results / $limit );
        $limit = "LIMIT $limit OFFSET $offset";
    }
    else
    {
        $offset = 0;
        $pages = 1;
    }

    // # Display search-string (if any)
    if ( $q ) echo "<i>Searching for: </i>\"$q\"<i> - Gave </i>$results <i>results</i><br><br>";

    echo "<a name=\"movies-list\" />\n";

    weebUIMovieListFunctions::moviesPageNavigatorHTML( $page, $pages );

    $res = $lib->query( $query = "SELECT * FROM items $SQLFilter ORDER BY item_name $limit" );
    while ( $data = sqlite_fetch_array( $res ) )
    {
        // # Formatting variables
        $genre = $data[$tag_Genre];
        if ( strstr( $genre, "|" ) )
        {
            $genre = substr( $genre, 1, strlen( $genre ) - 2 );
            $genre = str_replace( "|", ", ", $genre );
        }

        $id = $data['item_id'];
        // # Display items
        $rowSpan = 4;
        if ( $volumeName == '' )
            $rowSpan++;
        if ( !$unwatchedOnly )
            $rowSpan++;

        echo "<a name=#$id>\n";
        echo "<table width=\"100%\" style=\"margin-top: 30px; border: thin solid black;\">\n";
        echo "<tr>\n";
        echo "<td rowspan=\"{$rowSpan}\" width=\"150\" style=\"padding: 5px;\">\n";
        echo "<a href=\"" . weebUIMovieListFunctions::movieListURL( array( 'id' => $id ) ) . "\">";
        echo "<img src=\"thumb.php?id=" . $data['item_id'] . "&library=$library&VolumeName=$volumeName\" style=\"border: 0px solid black;\">\n";
        echo "</a>";
        echo "</td>\n";
        echo "<td><b>Title:</b></td>\n";
        echo "<td width=\"100%\">" . $data[$tag_Title] . "</td>\n";
        echo "</tr>\n";
        echo "<tr>\n";
        echo "<td><b>Genre:</b></td>\n";
        echo "<td width=\"100%\">$genre</td>\n";
        echo "</tr>\n";
        echo "<tr>\n";
        echo "<td><b>Runtime:</b></td>\n";
        echo "<td width=\"100%\">" . weebUIMovieListFunctions::formatRuntime( $data[$tag_Runtime] ) . "</td>\n";
        echo "</tr>\n";
        if ( $volumeName == '' )
        {
            echo "<tr>\n";
            echo "<td><b>Volume:</b></td>\n";
            echo "<td width=\"100%\">" . $data[$tag_VolumeName] . "</td>\n";
            echo "</tr>\n";
        }
        if ( !$unwatchedOnly )
        {
            echo "<tr>\n";
            echo "<td><b>Watched:</b></td>\n";
            echo "<td width=\"100%\">";
            echo ( $data[$tag_Watched] ? 'yes' : 'no' );
            if ( $data[$tag_WatchedOn] )
                echo " ({$data[$tag_WatchedOn]})";
            echo "</td>\n</tr>\n";
        }
        echo "<tr>\n";
        echo "<td><b>Actions:</b></td>\n";
        echo "<td width=\"100%\">\n";
        if ( session_is_registered( 'admin' ) )
        {
            echo "<button onclick=\"location.href = 'index.php?section=imdbsearch&id=$id&library=$library&VolumeName=$volumeName&name=" . $data['item_name'] . "'\">IMDB</button>";
            echo "<button onclick=\"window.open('do.php?what=play&type=movie&library=$library&VolumeName=$volumeName&id=$id','do')\">Play</button>\n";
            echo "<button onclick=\"location.href = 'do.php?what=update-tag&library=$library&id=$id&tag=$tag_Watched&value=".( $data[$tag_Watched] ? '' : 'True' )."'\">Mark as ". ( $data[$tag_Watched] ? 'unwatched' : 'watched' ) . "</button>\n";
        }
        if ( $lib->streaming == "1" )
        {
            $open = "window.open('player.php?library=$library&VolumeName=$volumeName&id=$id&type=movie', 'Movie', 'feature=status=0,toolbar=0,location=0,directories=0,menubar=0,scrollbars=0,resizable=1');";
            echo "<button onclick=\"$open\">Stream</button>\n";
        }
        echo "</td>\n";
        echo "</tr>";
        echo "</table>\n";
        echo "</a>\n";
    }

    weebUIMovieListFunctions::moviesPageNavigatorHTML( $page, $pages );
}
// #####################################
// #  DETAIL VIEW, MOVIE INFORMATION  ##
// #####################################
else
{
    $data = sqlite_fetch_array( $lib->query( "SELECT * FROM items WHERE item_id = '$id'" ) );
    $genre = $data[$tag_Genre];
    if ( strstr( $genre, "|" ) )
    {
        $genre = substr( $genre, 1, strlen( $genre ) - 2 );
        $genre = str_replace( "|", ", ", $genre );
    }
    $directors = $data[$tag_Director];
    if ( strstr( $directors, "|" ) )
    {
        $directors = substr( $directors, 1, strlen( $directors ) - 2 );
        $directors = str_replace( "|", " / ", $directors );
    }

    if ( strstr( $data[$tag_Actors], "|" ) )
    {
        $actorRoles = $data[$tag_ActorRoles];
        if ( strstr( $actorRoles, "|" ) )
        {
            $actorRoles = explode( '|', $actorRoles );
            array_pop( $actorRoles );
            array_shift( $actorRoles );
            $actorRoles = array_slice( $actorRoles, 0, 5, true);
        }
        $actors = explode( '|', $data[$tag_Actors] );
        array_pop( $actors );
        array_shift( $actors );
        $actors = array_slice( $actors, 0, 5, true );
        foreach ( $actors as $index => $actor )
        {
            $actorString = $actor;
            if ( isset( $actorRoles[$index] ) )
                $actorString .= " ({$actorRoles[$index]})";
            $actorsArray[] = $actorString;
        }
        $actors = implode( '<br />', $actorsArray );
    }
    // # Where am I?
    $res = $lib->query( "SELECT item_id FROM items ORDER BY item_name" );
    for ( $i = 1; $cnt = sqlite_fetch_array( $res ); $i++ )
    {
        if ( $cnt['item_id'] == $data['item_id'] ) $number = $i;
    }
    $where = ceil( $number / $lib->pagelimit );
    echo "<a href=\"index.php?section=library\">Library</a> -&gt; \n";
    echo "<a href=\"index.php?section=library&library=$library&VolumeName=$volumeName&page=$where#$id\">" . $lib->name . "</a> -&gt; \n";
    echo "<b>" . $data[$tag_Title] . "</b>\n";

    if ( $data['item_image'] )
    {
        echo "<table width=\"100%\">\n";
        echo "<tr>";
        echo "<td colspan=\"2\" align=\"center\" style=\"font-size: 24;\">" . $data['item_name'] . "</td>";
        echo "</tr>\n";

        echo "<tr>";
        echo "<td colspan=\"2\" align=\"center\"><img src=\"pic.php?library=$library&VolumeName=$volumeName&id=$id\"><br><br></td>";
        echo "</tr>\n";

        echo "</table>\n";
    }

    echo "<center>";
    if ( session_is_registered( 'admin' ) )
    {
        echo "<p>\n";
        echo "<form method=\"post\" action=\"do.php\" enctype=\"multipart/form-data\" />\n";
        echo "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"". 6 * 1024 * 1024 ."\" />\n";

        echo "<input type=\"hidden\" name=\"what\" value=\"change-image\" />\n";
        echo "<input type=\"hidden\" name=\"id\" value=\"$id\" />\n";
        echo "<input type=\"hidden\" name=\"library\" value=\"$library\" />\n";
        echo "<input type=\"file\" name=\"image\" />\n";
        echo "<input type=\"hidden\" name=\"movie-title\" value=\"" . htmlentities( $data[$tag_Title] ) . "\"/>\n";

        echo "<input type=\"submit\" value=\"Change image\" />\n";
        echo "</form>\n";
        echo "</p>\n";
    }

    if ( session_is_registered( 'admin' ) )
    {
        echo "<button onclick=\"location.href = 'index.php?section=imdbsearch&id=$id&library=$library&VolumeName=$volumeName&name=" . $data['item_name'] . "'\">IMDB</button>";
        echo "<button onclick=\"window.open('do.php?what=play&type=movie&library=$library&VolumeName=$volumeName&id=$id','do')\">Play</button>\n";
        echo "<button onclick=\"location.href = 'allocine.php?id=$id&library=$library'\" />Allocine sync</button>\n";
    }
    // # Streaming
    if ( $lib->streaming == "1" )
    {
        $open = "window.open('player.php?library=$library&VolumeName=$volumeName&id=$id&type=movie', 'Movie', 'feature=status=0,toolbar=0,location=0,directories=0,menubar=0,scrollbars=0,resizable=1');";
        echo "<button onclick=\"$open\">Stream</button>\n";
    }
    if ( ( session_is_registered( 'admin' ) ) && ( $edit != 1 ) )
    {
        echo "<button onclick=\"location.href = 'index.php?section=library&library=$library&VolumeName=$volumeName&id=$id&edit=1&page=$page&q=$q'\">Edit</button>";
    }
    echo "</center>";
    echo "<br>";

    // # archive movie form
    if ( ( session_is_registered( 'admin' ) ) && ( $edit != 1 ) )
    {
        echo "<script language=\"javascript\" src=\"js/movies.js\"></script>\n";

        echo "<center>\n";
        echo "<form method=\"get\" action=\"do.php\">\n";
        echo "<input type=\"hidden\" name=\"id\" value=\"{$id}\" />\n";
        echo "<input type=\"hidden\" name=\"what\" value=\"archive-movie\" />\n";
        echo "<input type=\"hidden\" name=\"from-volume\" value=\"{$data[$tag_VolumeName]}\" />\n";
        echo "<input type=\"hidden\" name=\"library\" value=\"{$library}\" />\n";
        echo "<input type=\"hidden\" name=\"location\" value=\"{$data['item_location']}\" />\n";
        echo "<input type=\"hidden\" name=\"item-ext-id\" value=\"{$data['item_ext_id']}\" />\n";
        echo "<input type=\"hidden\" name=\"tag-name\" value=\"{$tag_VolumeName}\" />\n";

        echo "<input id=\"ArchiveMovieButton\" type=\"submit\" value=\"Archive movie to...\" disabled=\"disabled\" />&nbsp;";

        echo "<select id=\"ArchiveMovieVolumesList\" name=\"to-volume\">\n";
        foreach ( weebUIVolumeManager::volumesList() as $volume )
        {
            // current volume is not selectable
            if ( $volume == $data[$tag_VolumeName] )
                echo "<option value=\"0\" selected=\"selected\">Select new volume</option>";
            else
                echo "<option value=\"{$volume}\">{$volume}</option>";
        }
        echo "</select>";
        echo "</form>\n";
        echo "</center>\n";
    }

    if ( $edit == 1 ) echo "<form method=\"post\" action=\"do.php?what=updatemovie&library=$library&VolumeName=$volumeName&id=$id&page=$page&q=$q\">";

    echo "<table border=\"1\" width=\"700\"align=\"center\" cellspacing=\"0\" cellpadding=\"10\">\n";

    if ( $data[$tag_Subtitle] )
    {
        echo "<tr>\n";
        echo "<td colspan=\"2\" align=\"center\">\n";
        if ( $edit == 1 ) echo "<input type=\"text\" size=\"56\" name=\"under\" value=\"" . htmlentities( addslashes( $data[$tag_Subtitle] ) ) . "\">\n";
        else echo "<b style=\"font-size: 16;\">" . $data[$tag_Subtitle] . "</b>";
        echo "</td>\n";
        echo "</tr>\n";
    }

    echo "<tr>\n";
    echo "<td align=\"right\" valign=\"top\" width=\"50%\"><b>Title:</b></td>\n";
    echo "<td width=\"30%\">";
    if ( $edit == 1 ) echo "<input type=\"text\" size=\"30\" name=\"title\" value=\"" . $data[$tag_Title] . "\">\n";
    else echo $data[$tag_Title];
    echo " </td>\n";
    echo "</tr>\n";

    echo "<tr>\n";
    echo "<td align=\"right\" valign=\"top\" width=\"50%\"><b>Volume name:</b></td>\n";
    echo "<td width=\"50%\">";
    if ( $edit == 1 ) echo "<input disabled=\"disabled\" type=\"text\" size=\"30\" name=\"volumeName\" value=\"" . $data[$tag_VolumeName] . "\">\n";
    else echo $data[$tag_VolumeName];
    echo " </td>\n";
    echo "</tr>\n";

    echo "<tr>\n";
    echo "<td align=\"right\" valign=\"top\" width=\"50%\"><b>Year:</b></td>\n";
    echo "<td width=\"50%\">";
    if ( $edit == 1 ) echo "<input type=\"text\" size=\"4\" name=\"produced\" value=\"" . $data[$tag_Produced] . "\">\n";
    else echo $data[$tag_Produced] ? $data[$tag_Produced] : 'N/A';
    echo " </td>\n";
    echo "</tr>\n";

    echo "<tr>\n";
    echo "<td align=\"right\" valign=\"top\" width=\"50%\"><b>Genre:</b></td>\n";
    echo "<td width=\"50%\">";
    if ( $edit == 1 ) echo "<input type=\"text\" size=\"30\" name=\"genre\" value=\"" . $data[$tag_Genre] . "\">\n";
    else echo $genre;
    echo "</td>\n";
    echo "</tr>\n";

    echo "<tr>\n";
    echo "<td align=\"right\" valign=\"top\" width=\"50%\"><b>Runtime:</b></td>\n";
    echo "<td width=\"50%\">";
    if ( $edit == 1 ) echo "<input type=\"text\" size=\"30\" name=\"runtime\" value=\"" . $data[$tag_Runtime] . "\">\n";
    else echo weebUIMovieListFunctions::formatRuntime( $data[$tag_Runtime] );
    echo " </td>\n";
    echo "</tr>\n";

    echo "<tr>\n";
    echo "<td align=\"right\" valign=\"top\" width=\"50%\"><b>Directed by:</b></td>\n";
    echo "<td width=\"50%\">";
    if ( $edit == 1 ) echo "<input type=\"text\" size=\"30\" name=\"director\" value=\"" . $data[$tag_Director] . "\">\n";
    else echo $directors;
    echo "</td>\n";
    echo "</tr>\n";

    echo "<tr>\n";
    echo "<td align=\"right\" valign=\"top\" width=\"50%\"><b>Actors:</b></td>\n";
    echo "<td width=\"50%\">";
    if ( $edit == 1 ) echo "<input type=\"text\" size=\"30\" name=\"actors\" value=\"" . $data[$tag_Actors] . "\">\n";
    else echo $actors;
    echo "</td>\n";
    echo "</tr>\n";

    echo "<tr>\n";
    echo "<td align=\"right\" valign=\"top\" width=\"50%\"><b>File size:</b></td>\n";
    echo "<td width=\"50%\">";
    echo weebUIMovieListFunctions::formatBytes( $data[$tag_Filesize] );
    echo "</td>\n";
    echo "</tr>\n";

    echo "<tr>\n";
    echo "<td colspan=\"2\" align=\"center\">\n";
    if ( $edit == 1 ) echo "<textarea name=\"plot\" cols=\"56\" rows=\"5\">" . stripslashes( $data[$tag_Overview] ) . "</textarea>\n";
    else echo stripslashes( $data[$tag_Overview] );
    echo "</td>\n";
    echo "</tr>\n";

    echo "</table>\n";
    echo "<center>\n";
    if ( $edit == 1 )
    {
        echo "<input type=\"submit\" value=\"Update\">\n";
        echo "</form>\n";
    }
    echo "</center>\n";
}

?>